
#import "YY_ImagePicker.h"

BOOL YY_UIAPP_CONTROLLER_PORTRAIT = NO;

static NSInteger* picWidth;
static NSInteger  *picHeight;

@interface YY_ImagePicker ()
@property (nonatomic, copy) void (^ completion)(NSString *, NSString *);


@end

@implementation YY_ImagePicker

+ (YY_ImagePicker *)getInstence {
    static YY_ImagePicker *inst = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        inst = [[YY_ImagePicker alloc] init];
    });
    return inst;
}

-(void)pickFromCamera:(NSInteger)pickSize scaleSize:(NSInteger)scaleSize completion:(void (^)(NSString *, NSString *))completion{
    if (YY_UIAPP_CONTROLLER_PORTRAIT){
        return;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        return;
    }
    
    self.completion = completion;
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    [imagePicker setShowsCameraControls:true];
    
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        [imagePicker setCameraDevice:UIImagePickerControllerCameraDeviceFront];
    } else {
        [imagePicker setCameraDevice:UIImagePickerControllerCameraDeviceRear];
    }
    
    [imagePicker setMediaTypes:[[NSArray alloc] initWithObjects:[NSString stringWithFormat:@"%@",kUTTypeImage],nil]];
    [imagePicker setAllowsEditing:true];
    [imagePicker setDelegate:self];
    
    UIViewController *viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if (viewController){
        YY_UIAPP_CONTROLLER_PORTRAIT = YES;
        [viewController presentViewController:imagePicker animated:true completion:nil];
    }
}

-(void)pickFromPhoto:(NSInteger)tempPicWidth :(NSInteger)tempPicHeight completion:(void (^)(NSString *, NSString *))completion{
    picWidth = tempPicWidth;
    picHeight = tempPicHeight;
    if (YY_UIAPP_CONTROLLER_PORTRAIT){
        return;
    }
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        return;
    }
    
    self.completion = completion;
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [imagePicker setAllowsEditing:true];
    [imagePicker setDelegate:self];
    
    UIViewController *viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    if (viewController){
        YY_UIAPP_CONTROLLER_PORTRAIT = YES;
        [viewController presentViewController:imagePicker animated:true completion:nil];

    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType = [NSString stringWithFormat:@"%@",info[UIImagePickerControllerMediaType]];;
    if ([mediaType isEqualToString:[NSString stringWithFormat:@"%@",kUTTypeImage]] &&
        [picker allowsEditing]){
        UIImage *image = (UIImage *)info[UIImagePickerControllerEditedImage];
        NSURL *tempDir = [NSURL URLWithString:NSTemporaryDirectory()];
        NSURL *bigPath = [tempDir URLByAppendingPathComponent:@"avatar_big.jpg"];
        NSURL *smallPath = [tempDir URLByAppendingPathComponent:@"avatar_small.jpg"];
        @try {
            NSString *picWidthStr = [NSString stringWithFormat:@"%ld", picWidth];
            CGFloat width = [picWidthStr floatValue];
            NSString *picHeightStr = [NSString stringWithFormat:@"%ld", picHeight];
            CGFloat height = [picHeightStr floatValue];
//            NSLog(@"abcd===========%f,%f", width, height);
            [self saveImage:image url:bigPath size:CGSizeMake(256,256) quality:0.8];
            [self saveImage:image url:smallPath size:CGSizeMake(width,height) quality:1.0];
            
            _completion(bigPath.absoluteString, smallPath.absoluteString);
            
        } @catch (NSException *exception) {
            _completion(@"", @"");
        }
    }
    
    YY_UIAPP_CONTROLLER_PORTRAIT = NO;
    [picker dismissViewControllerAnimated:true completion:nil];
}

-(void)saveImage:(UIImage *)image url:(NSURL *)url size:(CGSize)size quality:(CGFloat)quality{
    UIGraphicsBeginImageContext(size);
    CGRect rect =  CGRectMake(0, 0, size.width, size.height);
    [image drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSData *data = UIImageJPEGRepresentation(newImage,quality);
    @try {
        [data writeToURL:[NSURL URLWithString:[NSString stringWithFormat:@"file://%@",url.absoluteString]] options:NSDataWritingAtomic error:nil];
    } @catch (NSException *exception) {
        
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    YY_UIAPP_CONTROLLER_PORTRAIT = NO;
    [picker dismissViewControllerAnimated:true completion:nil];
}

-(void)dismissViewController:(UIImagePickerController *)picker{
    YY_UIAPP_CONTROLLER_PORTRAIT = NO;
    [picker dismissViewControllerAnimated:true completion:nil];
}

@end
